package base.controller;


import java.text.ParseException;

import demo.utils.DateUtil;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author : GuoFei
 * @date : 2018/12/21 18:12
 */

@Controller
public class DynamicCronTask implements SchedulingConfigurer {
    private static String cron = "0/10 * * * * ?";

    @RequestMapping("/setDynamicCronTask")
    public String setSpringDynamicCronTask(String setCron) throws ParseException {
        System.out.println("tttt");
        cron = setCron;
        System.err.println("cron change to:" + cron);
        return "test";
    }

    private void task(){
        System.out.println("nihao"+ DateUtil.getNow());
    }


    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegister) {
        taskRegister.addTriggerTask(this::task, triggerContext -> new CronTrigger(cron).nextExecutionTime(triggerContext));
    }


//    @Override
//    public void configureTasks(ScheduledTaskRegistrar taskRegister) {
//        taskRegister.addTriggerTask(new Runnable() {
//            @Override
//            public void run() {
//                // 逻辑任务
//                System.out.println("dynamicCronTask is running...");
//            }
//        }, new Trigger() {
//            @Override
//            public Date nextExecutionTime(TriggerContext triggerContext) {
//                // 任务触发，可修改任务的执行周期
//                CronTrigger trigger = new CronTrigger(cron);
//                System.out.println("cron:" + cron);
//                Date nextExecutor = trigger.nextExecutionTime(triggerContext);
//                return nextExecutor;
//            }
//        });
//    }


}
